'use strict';

/**
 * @name 通用筛选组件
 * @description 通用筛选组件
 * @author ZYF
 */
angular.module('metalabOperationApp').factory('MetaSearch', function() {
    var metaSearch = {};

    /**
     * @name 初始化
     * @description 初始化搜索模块，根据搜索配置，将默认搜索项设置为第一个可搜索选项，然后附上修改搜索项的方法，最后解析URL
     */
    metaSearch.initSearchModule = function(searchParams, searchConfig, stateParams, changeUrl) {
        metaSearch.buildSearchParams(searchParams, searchConfig, changeUrl);
        searchParams.changeSearchItem = metaSearch.changeSearchItem;
        if (stateParams) {
          metaSearch.decodeUrlSearchParams(searchParams, searchConfig, stateParams);
        }
    };

    /**
     * @name 创建搜索控制参数
     * @description 通用筛选组件
     */
    metaSearch.buildSearchParams = function(searchParams, searchConfig, changeUrl) {
      var init = false;
      angular.forEach(searchConfig, function(value, key) {
        if (init===false) {
          searchParams.name = value;
          searchParams.key = key;
          searchParams.data = [];
          searchParams.data[0] = value;
          init=true;
        } else {
          searchParams.data[searchParams.data.length] = value;
        }
      });
      searchParams.search = function(event){
        if (event.keyCode===13) {
          changeUrl();
        }
      };
    };

    /**
     * @name 改变搜索项目
     */
    metaSearch.changeSearchItem = function(searchConfig, searchParams, name) {
      searchParams.name = name;
      searchParams.value = '';
      angular.forEach(searchConfig, function(value, key) {
        if (value===name) {
          searchParams.key = key;
        }
      });
    };

    /**
     * @name 创建搜索控制参数
     * @description 通用筛选组件
     */
    metaSearch.decodeUrlSearchParams = function(searchParams, searchConfig, stateParams) {
      if (stateParams.search !== undefined) {
        searchParams.key = stateParams.search;
        searchParams.value = stateParams.value;
        searchParams.name = searchConfig[stateParams.search];
      }
    };

    /**
     * @description 增加搜索的URL参数
     */
    metaSearch.encodeUrlSearchParams = function(urlParams, searchParams) {
      if (searchParams.value!==undefined && searchParams.value!=='') {
        urlParams.search = searchParams.key;
        urlParams.value = searchParams.value;
      } else {
        urlParams.search = null;
        urlParams.value = null;
      }
    };

    return metaSearch;
});
